package com.sdy.hospitalguard.biz.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sdy.common.model.FileObj;
import com.sdy.common.utils.Assert;
import com.sdy.common.utils.DateUtil;
import com.sdy.hospitalguard.biz.constants.RedisConstants;
import com.sdy.hospitalguard.biz.mapper.HospitalUserMapper;
import com.sdy.hospitalguard.biz.model.HospitalUser;
import com.sdy.hospitalguard.biz.model.MatchingPeople;
import com.sdy.hospitalguard.biz.model.Qrcode;
import com.sdy.hospitalguard.biz.service.ApplyPostService;
import com.sdy.hospitalguard.biz.service.HospitalUserService;
import com.sdy.hospitalguard.biz.service.MatchingPeopleService;
import com.sdy.hospitalguard.biz.service.QrcodeService;
import com.sdy.hospitalguard.biz.utils.CardAnalysis;
import com.sdy.mvc.service.impl.BaseServiceImpl;
import com.sdy.redis.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 医院用户表 服务实现类
 * </p>
 *
 * @author zzq
 * @since 2020-05-08
 */
@Slf4j
@Service
public class HospitalUserServiceImpl extends BaseServiceImpl<HospitalUser> implements HospitalUserService {
    @Autowired
    private HospitalUserMapper hospitalUserMapper;
    @Autowired
    private HospitalUserService hospitalUserService;
    @Autowired
    private ApplyPostService applyPostService;
    @Autowired
    private MatchingPeopleService matchingPeopleService;
    @Autowired
    private QrcodeService qrcodeService;
    @Autowired
    private RedisService redisService;

    @Override
    public HospitalUser getUserByWxid(String wxid) {
        return lambdaQuery().eq(HospitalUser::getWxId, wxid).one();
    }

    @Override
    public HospitalUser xGetOrCreateUserByWxid(String wxid) {
        HospitalUser hospitalUser = getUserByWxid(wxid);
        if (hospitalUser == null) {
            hospitalUser = createUser(null, wxid);
        }
        return hospitalUser;
    }

    @Override
    public HospitalUser createUser(String phone, String wxid) {
        HospitalUser user = new HospitalUser()
                .setPhone(phone)
                .setWxId(wxid)
                .setCreateTime(new Date());
        save(user);
        return user;
    }

    @Override
    public HospitalUser getUserByPhone(String phone) {
        return lambdaQuery().eq(HospitalUser::getPhone, phone).one();
    }

    @Override
    public HospitalUser getUserByIdCard(String idCard) {
        return lambdaQuery().eq(HospitalUser::getIdCard, idCard).one();
    }

    @Override
    public Boolean userRegister(HospitalUser hospitalUser, Integer userId) throws Exception {
        SimpleDateFormat dateFormat = new SimpleDateFormat(DateUtil.DATETIME_FORMAT);
        HospitalUser sexAge = CardAnalysis.getCard(hospitalUser.getIdCard());
        // 获取头像地址
        String path = null;
        if (StringUtils.isNotBlank(hospitalUser.getHeadPortrait())) {
            FileObj fileObj = redisService.get(RedisConstants.FILE_UPLOAD_UUID + hospitalUser.getHeadPortrait(), FileObj.class);
            path = fileObj.getPath();
        }
        hospitalUserService.lambdaUpdate()
                .eq(HospitalUser::getId, userId)
                .set(HospitalUser::getName, hospitalUser.getName())
                .set(HospitalUser::getSex, sexAge.getSex())
                .set(HospitalUser::getAge, sexAge.getAge())
                .set(HospitalUser::getIdCard, hospitalUser.getIdCard())
                .set(HospitalUser::getPhone, hospitalUser.getPhone())
                .set(HospitalUser::getUserState, 0)
                .set(HospitalUser::getHeadPortrait, hospitalUser.getHeadPortrait())
                .set(HospitalUser::getPhotoPath, path)
                .set(HospitalUser::getCreateTime, dateFormat.format(new Date()))
                .update();
        // 此人目前的身份(0-无直接关系 1-患者 2-陪护 3-探视人员 4-陪护+探视)
        Integer identity = applyPostService.checkIdentity(userId);
        if (identity != 0) {
            // 如果这个人有身份，更新数据，并且在matchingPeople存在有效数据
            // 找到每条是我的matchingPeople数据
            List<MatchingPeople> list = matchingPeopleService.list(Wrappers.<MatchingPeople>lambdaQuery()
                    .eq(MatchingPeople::getUserId, userId));
            for (MatchingPeople l : list) {
                // 更新机器数据
                MatchingPeople matchingPeople = new MatchingPeople()
                        .setUserId(userId)
                        .setName(hospitalUser.getName())
                        .setCardId(hospitalUser.getIdCard())
                        .setFaceId(userId)
                        .setPhotoPath(path)
                        .setQrcodeContent(l.getQrcodeContent())
                        .setRemark(l.getRemark())
                        .setBuilding(l.getBuilding())
                        .setLastChange(System.currentTimeMillis() / 1000 + "")
                        .setStatus(0);
                boolean add = matchingPeopleService.add(matchingPeople);
                Assert.notTrue(add, "matchingPeople新增陪护数据失败!");
                log.info("userRegister-修改数据同步到机器成功！");
            }
        }
        // 检查这个人是否具有通行码，没有则生成
        Qrcode one = qrcodeService.getOne(Wrappers.<Qrcode>lambdaQuery().eq(Qrcode::getUserId, userId));
        Boolean aBoolean;
        if (one == null) {
            aBoolean = applyPostService.createQRcode(userId);
            Assert.notTrue(aBoolean, "生成通行码失败!");
        }
        return true;
    }

}
